package handler.server;


import event.SwordAllMsgEvent;
import event.SwordRegisterEvent;
import event.SwordSendMsgEvent;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class SwordServerHandler extends ChannelInboundHandlerAdapter {

	public SwordServerHandler() {
		super();
	}

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		//  连接建立时触发
		super.channelRegistered(ctx);
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		// 连接断开时触发
		super.channelUnregistered(ctx);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// 客户端和服务端建立连接
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// 客户端主动断开连接时触发
		super.channelInactive(ctx);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// 客户端发送请求时触发
		String message = (String) msg;
//		System.out.println(ctx.channel().remoteAddress()+" : "+message);
		if(message.startsWith("id")) ctx.fireUserEventTriggered(new SwordRegisterEvent(message.split(":")[1]));
		if(message.startsWith("all")) ctx.fireUserEventTriggered(new SwordAllMsgEvent(message));
		if(message.startsWith("send")) {
			String[] split = message.split(",");
			String id = split[0].split(":")[1];
			String sendMsg = split[1].split(":")[1];
			ctx.fireUserEventTriggered(
					new SwordSendMsgEvent(id, sendMsg)
			);

		}
		super.channelRead(ctx, msg);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// 读取完毕后触发
		super.channelReadComplete(ctx);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		// 用户事件触发时触发
		super.userEventTriggered(ctx, evt);
	}

	@Override
	public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
		// 可写事件触发时触发
		super.channelWritabilityChanged(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// 异常捕获时触发
		Channel channel = ctx.channel();
		if (channel.isActive()) ctx.close();
//		super.exceptionCaught(ctx, cause);
	}
}
